package com.example.cms;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
@SuppressWarnings("deprecation")
public class KsoapClient {
	private String SOAP_ACTION;
	private String METHOD_NAME;
	private String NAMESPACE;
	private String URL;
	private SoapObject Request;
	private SoapSerializationEnvelope soapEnvelope;
	private AndroidHttpTransport aht;
	
	public KsoapClient (String url, String namespace) {
		this.URL = url;
		this.NAMESPACE = namespace;		
	}
	
	public void setMethod(String soap_action, String method_name) {
		this.SOAP_ACTION = soap_action;
		this.METHOD_NAME = method_name;
		Request = new SoapObject(this.NAMESPACE, this.METHOD_NAME);
		soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		soapEnvelope.dotNet = true;
		aht = new AndroidHttpTransport(URL);
	}
	
	public void addProp(String arg, String value) {
		Request.addProperty(arg, value);
	}
	
	public void addPropInt(String arg, int value) {
		Request.addProperty(arg, value);
	}
	public void addPropBool(String arg, boolean value) {
		Request.addProperty(arg, value);
	}
	
	public String connect() {
		
		soapEnvelope.setOutputSoapObject(Request);
		try {
			
			aht.call(SOAP_ACTION, soapEnvelope);
			SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
			return resultString.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}
	
	public String[] connectMultiple() {
		soapEnvelope.setOutputSoapObject(Request);
		System.out.println("connectMultiple: entra al try");
		try {			
			aht.call(SOAP_ACTION, soapEnvelope);
			System.out.println("connectMultiple: Call executat");
			SoapObject response = (SoapObject) soapEnvelope.bodyIn;System.out.println("connectMultiple: soapobject response");
			int numelem = response.getPropertyCount();
			System.out.println("Response te el seguent numero d'elements: " + numelem);
			if (numelem < 1) {
				String[] result = new String[1];
				result[0] = "error";
				return result;
			}
			String[] resultArray = new String[numelem];
			for (int i = 0; i < numelem; ++i) {
				SoapPrimitive elem = (SoapPrimitive) response.getProperty(i);
				resultArray[i] = elem.toString();
				System.out.println(resultArray[i]);
			}
			return resultArray;			
		} catch (Exception e) {
			e.printStackTrace();
			String[] resultArray = new String[1];
			resultArray[0] = "error";
			return resultArray;
			//return "error";
		}		
	}
}